package com.cy.jt.jt.security.config.hander;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
/**登陆成功以后返回一个json数据*/
public class DefaultRedirectAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //可以在这样的方法中 获取登陆用户的信息
        //获取用户身份(principal-身份的意思)
        User principal = (User) authentication.getPrincipal();
        System.out.println(principal.getUsername()+","+principal.getPassword()+","+principal.getAuthorities());//用户权限
        //获取用户凭证(默认为密码,credentials-凭证的意思)
        Object credenttials = authentication.getCredentials();
        System.out.println(principal);
        System.out.println(credenttials);
        //设置响应数据的编码
        httpServletResponse.setCharacterEncoding("utf-8");
        //告诉客户端响应数据的类型,以及客户端以怎样的编码进行显示
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //获取一个输出流对象
        PrintWriter out = httpServletResponse.getWriter();
        Map<String,String>map = new HashMap<>();
        map.put("state", "200");
        map.put("msg", "Login ok");
        //基于jackson中的ObjectMapper对象将一个对象转换为json格式字符串
        String str = new ObjectMapper().writeValueAsString(map);
        out.println(str);
        //out.println("{\"state\":200,\"msg\":\"ok\"}");
        out.flush();
    }
}
